<template>
  <div class="sales-statistics-container">
    <a-card :bordered="false">
      <!-- 查询表单 -->
      <a-form layout="inline" :model="queryParams" @finish="handleQuery" class="search-form">
        <a-form-item label="统计类型" name="statisticsType">
          <a-select v-model:value="queryParams.statisticsType" placeholder="请选择统计类型" style="width: 150px">
            <a-select-option value="week">按周</a-select-option>
            <a-select-option value="month">按月</a-select-option>
            <a-select-option value="quarter">按季度</a-select-option>
            <a-select-option value="year">按年</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="销售人员" name="salespersonId">
          <a-select
            v-model:value="queryParams.salespersonId"
            placeholder="请选择销售人员（不选则统计全公司）"
            style="width: 250px"
            allow-clear
            show-search
            option-filter-prop="label"
          >
            <a-select-option
              v-for="user in userList"
              :key="user.userId"
              :value="user.userId"
              :label="user.nickName || user.userName"
            >
              {{ user.nickName || user.userName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item v-if="queryParams.statisticsType !== 'year'" label="日期" name="date">
          <a-date-picker
            v-model:value="queryParams.date"
            format="YYYY-MM-DD"
            placeholder="选择日期"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item v-if="queryParams.statisticsType === 'year'" label="年份" name="year">
          <a-input-number
            v-model:value="queryParams.year"
            placeholder="请输入年份"
            :min="2000"
            :max="2100"
            style="width: 200px"
          />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit">
              <template #icon><search-outlined /></template>
              查询
            </a-button>
            <a-button @click="resetQuery">
              <template #icon><redo-outlined /></template>
              重置
            </a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <!-- 基本数据卡片 -->
      <a-row :gutter="16" class="statistics-cards">
        <a-col :span="6">
          <a-card class="stat-card">
            <a-statistic
              title="总营业额"
              :value="Number(statisticsData.totalSalesAmount || 0)"
              :precision="2"
              prefix="¥"
              :value-style="{ color: '#3f8600' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <a-statistic
              title="成交客户数"
              :value="statisticsData.completedCustomerCount || 0"
              :value-style="{ color: '#1890ff' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <a-statistic
              title="成交订单数"
              :value="statisticsData.completedOrderCount || 0"
              :value-style="{ color: '#722ed1' }"
            />
          </a-card>
        </a-col>
        <a-col :span="6">
          <a-card class="stat-card">
            <a-statistic
              title="成交率"
              :value="statisticsData.successRate || 0"
              :precision="2"
              suffix="%"
              :value-style="{ color: '#cf1322' }"
            />
          </a-card>
        </a-col>
      </a-row>

      <!-- 图表区域 -->
      <a-row :gutter="16" class="charts-row">
        <!-- 营业额趋势图（折线图） -->
        <a-col :span="12">
          <a-card title="营业额趋势" :bordered="false">
            <div ref="salesAmountChartRef" style="width: 100%; height: 300px;"></div>
          </a-card>
        </a-col>
        <!-- 订单数趋势图（柱状图） -->
        <a-col :span="12">
          <a-card title="订单数趋势" :bordered="false">
            <div ref="orderCountChartRef" style="width: 100%; height: 300px;"></div>
          </a-card>
        </a-col>
      </a-row>

      <a-row :gutter="16" class="charts-row">
        <!-- 销售人员业绩分布（饼图） -->
        <a-col :span="12">
          <a-card title="销售人员业绩分布" :bordered="false">
            <div ref="salespersonPieChartRef" style="width: 100%; height: 300px;"></div>
          </a-card>
        </a-col>
        <!-- 销售人员订单数（柱状图） -->
        <a-col :span="12">
          <a-card title="销售人员订单数" :bordered="false">
            <div ref="salespersonOrderChartRef" style="width: 100%; height: 300px;"></div>
          </a-card>
        </a-col>
      </a-row>

      <!-- 详细数据表格 -->
      <a-card title="时间序列数据" :bordered="false" class="table-card">
        <a-table
          :columns="timeSeriesColumns"
          :data-source="statisticsData.timeSeriesData || []"
          :pagination="false"
          :loading="loading"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'salesAmount'">
              ¥{{ Number(record.salesAmount || 0).toFixed(2) }}
            </template>
          </template>
        </a-table>
      </a-card>

      <a-card title="销售人员数据" :bordered="false" class="table-card">
        <a-table
          :columns="salespersonColumns"
          :data-source="statisticsData.salespersonData || []"
          :pagination="false"
          :loading="loading"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'salesAmount'">
              ¥{{ Number(record.salesAmount || 0).toFixed(2) }}
            </template>
          </template>
        </a-table>
      </a-card>
    </a-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, nextTick, watch } from 'vue'
import { message } from 'ant-design-vue'
import { SearchOutlined, RedoOutlined } from '@ant-design/icons-vue'
import * as salesStatisticsApi from '@/api/sales-statistics'
import * as userApi from '@/api/user'
import type { SysUser } from '@/types/user'
import dayjs from 'dayjs'
import type { Dayjs } from 'dayjs'

// 加载状态
const loading = ref(false)

// 统计数据
const statisticsData = ref<any>({
  totalSalesAmount: 0,
  completedCustomerCount: 0,
  completedOrderCount: 0,
  refundedOrderCount: 0,
  totalOrderCount: 0,
  successRate: 0,
  timeSeriesData: [],
  salespersonData: []
})

// 用户列表
const userList = ref<SysUser[]>([])

// 查询参数
const queryParams = reactive({
  statisticsType: 'month', // 默认按月
  salespersonId: undefined as number | undefined,
  date: undefined as Dayjs | undefined,
  year: undefined as number | undefined
})

// 图表引用
const salesAmountChartRef = ref<HTMLElement>()
const orderCountChartRef = ref<HTMLElement>()
const salespersonPieChartRef = ref<HTMLElement>()
const salespersonOrderChartRef = ref<HTMLElement>()

// 时间序列表格列
const timeSeriesColumns = [
  {
    title: '时间',
    dataIndex: 'timeLabel',
    key: 'timeLabel'
  },
  {
    title: '营业额',
    dataIndex: 'salesAmount',
    key: 'salesAmount'
  },
  {
    title: '订单数',
    dataIndex: 'orderCount',
    key: 'orderCount'
  }
]

// 销售人员表格列
const salespersonColumns = [
  {
    title: '销售人员',
    dataIndex: 'salespersonName',
    key: 'salespersonName'
  },
  {
    title: '营业额',
    dataIndex: 'salesAmount',
    key: 'salesAmount'
  },
  {
    title: '订单数',
    dataIndex: 'orderCount',
    key: 'orderCount'
  }
]

// 初始化：设置默认日期和年份
const initDefaultParams = () => {
  const now = dayjs()
  queryParams.date = now
  queryParams.year = now.year()
}

// 加载用户列表
const loadUserList = async () => {
  try {
    const users = await userApi.getUserList()
    userList.value = users || []
  } catch (error) {
    console.error('加载用户列表失败:', error)
  }
}

// 查询统计数据
const getStatistics = async () => {
  loading.value = true
  try {
    const params: any = {
      statisticsType: queryParams.statisticsType
    }
    
    if (queryParams.salespersonId) {
      params.salespersonId = queryParams.salespersonId
    }
    
    // 根据统计类型传递日期或年份
    if (queryParams.statisticsType === 'year') {
      if (queryParams.year) {
        params.year = queryParams.year
      }
    } else {
      // 按周、按月、按季度都传日期
      if (queryParams.date) {
        params.date = queryParams.date.format('YYYY-MM-DD')
      }
    }

    const res = await salesStatisticsApi.getSalesStatistics(params)
    statisticsData.value = res || {}
    
    // 更新图表
    await nextTick()
    updateCharts()
  } catch (error) {
    message.error('获取统计数据失败')
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 更新图表（使用简单的HTML/CSS展示，如果需要更复杂的图表可以安装ECharts）
const updateCharts = () => {
  // 这里可以使用简单的HTML/CSS或者安装ECharts来展示图表
  // 由于项目中没有ECharts，这里先使用简单的展示方式
  // 如果需要图表，可以安装: npm install echarts vue-echarts
}

// 查询
const handleQuery = () => {
  getStatistics()
}

// 重置查询
const resetQuery = () => {
  queryParams.statisticsType = 'month'
  queryParams.salespersonId = undefined
  initDefaultParams()
  getStatistics()
}

// 监听统计类型变化，重置日期/年份
watch(() => queryParams.statisticsType, () => {
  if (queryParams.statisticsType === 'year') {
    queryParams.date = undefined
    if (!queryParams.year) {
      queryParams.year = dayjs().year()
    }
  } else {
    queryParams.year = undefined
    if (!queryParams.date) {
      queryParams.date = dayjs()
    }
  }
})

// 初始化
onMounted(() => {
  initDefaultParams()
  loadUserList()
  getStatistics()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}

.statistics-cards {
  margin-bottom: 20px;
}

.stat-card {
  text-align: center;
}

.charts-row {
  margin-bottom: 20px;
}

.table-card {
  margin-top: 20px;
}
</style>

